<template>
  <PageContainer title="异常投递列表">
    <!-- 搜索筛选区域 -->
    <SearchForm v-model="searchForm" @search="handleSearch" @reset="handleReset">
      <el-form-item label="用户筛选">
        <el-input
          v-model="searchForm.userName"
          placeholder="请输入用户名或手机号"
          clearable
        />
      </el-form-item>
      <el-form-item label="设备筛选">
        <el-select
          v-model="searchForm.deviceId"
          placeholder="请选择设备"
          clearable
        >
          <el-option
            v-for="device in deviceOptions"
            :key="device.id"
            :label="device.name"
            :value="device.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="异常类型">
        <el-select
          v-model="searchForm.exceptionType"
          placeholder="请选择异常类型"
          clearable
        >
          <el-option label="重量异常" value="weight_error" />
          <el-option label="类型异常" value="type_error" />
          <el-option label="金额异常" value="amount_error" />
        </el-select>
      </el-form-item>
      <el-form-item label="处理状态">
        <el-select
          v-model="searchForm.status"
          placeholder="请选择处理状态"
          clearable
        >
          <el-option label="待处理" value="pending" />
          <el-option label="处理中" value="processing" />
          <el-option label="已处理" value="completed" />
          <el-option label="已忽略" value="ignored" />
        </el-select>
      </el-form-item>
      <el-form-item label="时间范围">
        <el-date-picker
          v-model="searchForm.dateRange"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
        />
      </el-form-item>
    </SearchForm>

    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="action-left">
        <el-button
          type="primary"
          @click="handleCreateException"
        >
          <el-icon><Plus /></el-icon>
          新增异常
        </el-button>
        <el-button
          type="primary"
          :disabled="!selectedRows.length"
          @click="handleBatchProcess"
        >
          <el-icon><Operation /></el-icon>
          批量处理
        </el-button>
        <el-button
          type="success"
          @click="handleExport"
        >
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
      <div class="action-right">
        <el-button
          type="info"
          @click="loadExceptionList"
        >
          <el-icon><Refresh /></el-icon>
          刷新
        </el-button>
      </div>
    </div>

    <!-- 异常投递列表表格 -->
    <DataTable
      :data="exceptionList"
      :loading="loading"
      :pagination="pagination"
      @page-change="handlePageChange"
      @size-change="handleSizeChange"
      @selection-change="handleSelectionChange"
    >
      <el-table-column type="selection" width="55" />
      <el-table-column prop="id" label="异常ID" width="100" />
      <el-table-column label="投递时间" width="180">
        <template #default="{ row }">
          {{ formatDateTime(row.createdAt) }}
        </template>
      </el-table-column>
      <el-table-column label="用户信息" width="150">
        <template #default="{ row }">
          <div>{{ row.userName }}</div>
          <div class="text-secondary">{{ row.userPhone }}</div>
        </template>
      </el-table-column>
      <el-table-column label="所在小区" width="150">
        <template #default="{ row }">
          {{ row.communityName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="设备信息" width="150">
        <template #default="{ row }">
          <div>{{ row.deviceName }}</div>
          <div class="text-secondary">{{ row.deviceCode }}</div>
        </template>
      </el-table-column>
      <el-table-column label="布袋编号" width="120">
        <template #default="{ row }">
          <div>{{ row.bagNumber || '-' }}</div>
        </template>
      </el-table-column>
      <el-table-column label="异常类型" width="120">
        <template #default="{ row }">
          <el-tag :type="getExceptionTypeTag(row.type)">
            {{ getExceptionTypeText(row.type) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="投放信息" width="200">
        <template #default="{ row }">
          <div>类型: {{ row.wasteType }}</div>
          <div>重量: {{ row.weight }}kg</div>
          <div>金额: ¥{{ row.originalAmount }}</div>
          <div v-if="row.adjustAmount !== undefined" :class="{'text-success': row.adjustAmount > 0, 'text-danger': row.adjustAmount < 0}">
            调整: {{ row.adjustAmount > 0 ? '+' : '' }}{{ row.adjustAmount.toFixed(2) }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="调整金额" width="120">
        <template #default="{ row }">
          <div v-if="row.adjustAmount !== undefined" :class="{'text-success': row.adjustAmount > 0, 'text-danger': row.adjustAmount < 0}">
            {{ row.adjustAmount > 0 ? '+' : '' }}{{ row.adjustAmount.toFixed(2) }}
          </div>
          <div v-else class="text-secondary">-</div>
        </template>
      </el-table-column>
      <el-table-column label="异常描述" min-width="200">
        <template #default="{ row }">
          <el-tooltip :content="row.description" placement="top">
            <div class="text-ellipsis">{{ row.description }}</div>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column label="图片" width="100">
        <template #default="{ row }">
          <div v-if="row.images && row.images.length > 0">
            <el-image
              :src="row.images[0]"
              :preview-src-list="row.images"
              style="width: 40px; height: 40px; border-radius: 4px;"
              fit="cover"
            >
              <template #error>
                <div class="image-error">图片</div>
              </template>
            </el-image>
            <span class="image-count" v-if="row.images.length > 1">+{{ row.images.length - 1 }}</span>
          </div>
          <div v-else class="text-secondary">-</div>
        </template>
      </el-table-column>
      <el-table-column label="处理状态" width="100">
        <template #default="{ row }">
          <el-tag :type="getStatusTag(row.status)">
            {{ getStatusText(row.status) }}
          </el-tag>
        </template>
      </el-table-column>
      <el-table-column label="质检员" width="100">
        <template #default="{ row }">
          {{ row.inspectorName || '-' }}
        </template>
      </el-table-column>
      <el-table-column label="操作" width="200" fixed="right">
        <template #default="{ row }">
          <el-button
            type="primary"
            size="small"
            @click="handleProcess(row)"
            :disabled="row.status === 'completed'"
          >
            处理
          </el-button>
          <el-button
            type="info"
            size="small"
            @click="handleViewDetail(row)"
          >
            详情
          </el-button>
          <el-dropdown @command="(command: string) => handleMoreAction(command, row)">
            <el-button type="text" size="small">
              更多<el-icon><ArrowDown /></el-icon>
            </el-button>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item command="ignore" :disabled="row.status === 'completed'">
                  忽略
                </el-dropdown-item>
                <el-dropdown-item command="reassign">
                  重新分配
                </el-dropdown-item>
                <el-dropdown-item command="history">
                  处理历史
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
      </el-table-column>
    </DataTable>

    <!-- 处理对话框 -->
    <el-dialog
      v-model="processDialogVisible"
      title="异常处理"
      width="80%"
      :close-on-click-modal="false"
    >
      <div class="process-dialog-content">
        <p>质检处理功能已移除</p>
        <div class="dialog-actions">
          <el-button @click="processDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="processDialogVisible = false">确定</el-button>
        </div>
      </div>
    </el-dialog>

    <!-- 详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="异常详情"
      width="60%"
    >
      <div v-if="currentException" class="exception-detail">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="异常ID">
            {{ currentException.id }}
          </el-descriptions-item>
          <el-descriptions-item label="投递时间">
            {{ formatDateTime(currentException.createdAt) }}
          </el-descriptions-item>
          <el-descriptions-item label="用户信息">
            {{ currentException.userName }} ({{ currentException.userPhone }})
          </el-descriptions-item>
          <el-descriptions-item label="设备信息">
            {{ currentException.deviceName }} ({{ currentException.deviceCode }})
          </el-descriptions-item>
          <el-descriptions-item label="异常类型">
            <el-tag :type="getExceptionTypeTag(currentException.type)">
              {{ getExceptionTypeText(currentException.type) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="处理状态">
            <el-tag :type="getStatusTag(currentException.status)">
              {{ getStatusText(currentException.status) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="投放重量">
            {{ currentException.weight }}kg
          </el-descriptions-item>
          <el-descriptions-item label="原始金额">
            ¥{{ currentException.originalAmount }}
          </el-descriptions-item>
          <el-descriptions-item label="异常描述" :span="2">
            {{ currentException.description }}
          </el-descriptions-item>
        </el-descriptions>

        <div v-if="currentException.images?.length" class="exception-images">
          <h4>相关图片</h4>
          <div class="images-grid">
            <el-image
              v-for="(image, index) in currentException.images"
              :key="index"
              :src="image"
              :preview-src-list="currentException.images"
              class="exception-image"
              fit="cover"
            />
          </div>
        </div>
      </div>
    </el-dialog>

    <!-- 新增异常对话框 -->
    <el-dialog
      v-model="createExceptionDialogVisible"
      title="新增异常"
      width="90%"
      :close-on-click-modal="false"
    >
      <div class="create-exception-dialog">
        <!-- 投递记录列表 -->
        <div class="delivery-records-section">
          <h4>用户投递记录</h4>
          <div class="search-bar">
            <el-input
              v-model="deliverySearchForm.bagNumber"
              placeholder="搜索布袋编号"
              style="width: 200px; margin-right: 12px;"
              @input="handleDeliverySearch"
            />
            <el-button type="primary" @click="handleScanBagNumber">
              <el-icon><Camera /></el-icon>
              扫码
            </el-button>
            <el-input
              v-model="deliverySearchForm.userName"
              placeholder="搜索用户名或手机号"
              style="width: 200px;"
              @input="handleDeliverySearch"
            />
          </div>
          <el-table
            :data="deliveryRecords"
            highlight-current-row
            @current-change="handleDeliveryRecordSelect"
            style="width: 100%; margin-top: 12px;"
          >
            <el-table-column prop="bagNumber" label="布袋编号" width="120" />
            <el-table-column label="用户信息" width="150">
              <template #default="{ row }">
                <div>{{ row.userName }}</div>
                <div class="text-secondary">{{ row.userPhone }}</div>
              </template>
            </el-table-column>
            <el-table-column label="所在小区" width="120">
              <template #default="{ row }">
                {{ row.communityName || '-' }}
              </template>
            </el-table-column>
            <el-table-column label="设备信息" width="150">
              <template #default="{ row }">
                <div>{{ row.deviceName }}</div>
                <div class="text-secondary">{{ row.deviceCode }}</div>
              </template>
            </el-table-column>
            <el-table-column prop="wasteType" label="回收类型" width="100" />
            <el-table-column prop="weight" label="重量(kg)" width="100">
              <template #default="{ row }">
                {{ row.weight }}
              </template>
            </el-table-column>
            <el-table-column prop="amount" label="金额(元)" width="100">
              <template #default="{ row }">
                ¥{{ row.amount }}
              </template>
            </el-table-column>
            <el-table-column label="图片" width="80">
              <template #default="{ row }">
                <div v-if="row.images && row.images.length > 0">
                  <el-image
                    :src="row.images[0]"
                    :preview-src-list="row.images"
                    style="width: 30px; height: 30px; border-radius: 4px;"
                    fit="cover"
                  >
                    <template #error>
                      <div style="width: 30px; height: 30px; display: flex; align-items: center; justify-content: center; background: #f5f7fa; border-radius: 4px; color: #909399; font-size: 10px;">图片</div>
                    </template>
                  </el-image>
                  <span style="margin-left: 2px; font-size: 10px; color: #409eff; font-weight: bold;" v-if="row.images.length > 1">+{{ row.images.length - 1 }}</span>
                </div>
                <div v-else class="text-secondary">-</div>
              </template>
            </el-table-column>
            <el-table-column prop="deliveryTime" label="投递时间" width="180">
              <template #default="{ row }">
                {{ formatDateTime(row.deliveryTime) }}
              </template>
            </el-table-column>
          </el-table>
        </div>

        <!-- 异常信息表单 -->
        <div v-if="selectedDeliveryRecord" class="exception-form-section">
          <h4>异常信息</h4>
          <el-form :model="createExceptionForm" label-width="100px">
            <el-form-item label="异常类型">
              <el-select v-model="createExceptionForm.type" placeholder="请选择异常类型">
                <el-option label="重量异常" value="weight_error" />
                <el-option label="类型异常" value="type_error" />
                <el-option label="金额异常" value="amount_error" />
                <el-option label="其他异常" value="other" />
              </el-select>
            </el-form-item>
            <el-form-item label="调整金额">
              <el-input-number
                v-model="createExceptionForm.adjustAmount"
                :precision="2"
                :step="0.1"
                placeholder="请输入调整金额"
                style="width: 200px;"
              />
              <span class="amount-hint" :class="{'positive': createExceptionForm.adjustAmount > 0, 'negative': createExceptionForm.adjustAmount < 0}">
                {{ createExceptionForm.adjustAmount > 0 ? '+' : '' }}{{ createExceptionForm.adjustAmount.toFixed(2) }}
              </span>
            </el-form-item>
            <el-form-item label="异常原因">
              <el-input
                v-model="createExceptionForm.reason"
                type="textarea"
                :rows="3"
                placeholder="请输入异常原因"
              />
            </el-form-item>
            <el-form-item label="详细描述">
              <el-input
                v-model="createExceptionForm.description"
                type="textarea"
                :rows="4"
                placeholder="请输入异常详细描述"
              />
            </el-form-item>
          </el-form>
        </div>

        <!-- 操作按钮 -->
        <div class="dialog-actions">
          <el-button @click="createExceptionDialogVisible = false">取消</el-button>
          <el-button
            type="primary"
            :disabled="!selectedDeliveryRecord"
            @click="handleCreateExceptionSubmit"
          >
            创建异常
          </el-button>
        </div>
      </div>
    </el-dialog>
  </PageContainer>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Operation,
  Download,
  Refresh,
  ArrowDown,
  Plus,
  Camera
} from '@element-plus/icons-vue'
import PageContainer from '@/components/PageContainer.vue'
import SearchForm from '@/components/SearchForm.vue'
import DataTable from '@/components/DataTable.vue'

import { useQualityStore } from '@/stores/quality'
import { formatDateTime } from '@/utils'
import type { QualityException, UserDeliveryRecord, CreateExceptionForm } from '@/types/quality'

const qualityStore = useQualityStore()

const loading = ref(false)
const processDialogVisible = ref(false)
const detailDialogVisible = ref(false)
const currentException = ref<QualityException | null>(null)
const selectedRows = ref<QualityException[]>([])

// 新增异常相关状态
const createExceptionDialogVisible = ref(false)
const deliveryRecords = ref<UserDeliveryRecord[]>([])
const selectedDeliveryRecord = ref<UserDeliveryRecord | null>(null)
const createExceptionForm = reactive<CreateExceptionForm>({
  deliveryRecordId: 0,
  type: 'weight_error',
  description: '',
  adjustAmount: 0,
  reason: ''
})

// 搜索表单
const searchForm = reactive({
  userName: '',
  deviceId: '',
  exceptionType: '',
  status: '',
  dateRange: []
})

// 投递记录搜索表单
const deliverySearchForm = reactive({
  bagNumber: '',
  userName: ''
})



// 分页信息
const pagination = reactive({
  page: 1,
  size: 20,
  total: 0
})

// 异常列表
const exceptionList = ref<QualityException[]>([])

// 设备选项
const deviceOptions = ref([
  { id: 1, name: '设备A-001' },
  { id: 2, name: '设备B-002' },
  { id: 3, name: '设备C-003' }
])

// 获取异常类型标签
const getExceptionTypeTag = (type: string) => {
  switch (type) {
    case 'weight_error':
      return 'warning'
    case 'type_error':
      return 'danger'
    case 'amount_error':
      return 'info'
    default:
      return 'info'
  }
}

// 获取异常类型文本
const getExceptionTypeText = (type: string) => {
  switch (type) {
    case 'weight_error':
      return '重量异常'
    case 'type_error':
      return '类型异常'
    case 'amount_error':
      return '金额异常'
    default:
      return '其他异常'
  }
}

// 获取状态标签
const getStatusTag = (status: string) => {
  switch (status) {
    case 'pending':
      return 'warning'
    case 'processing':
      return 'primary'
    case 'completed':
      return 'success'
    case 'ignored':
      return 'info'
    default:
      return 'info'
  }
}

// 获取状态文本
const getStatusText = (status: string) => {
  switch (status) {
    case 'pending':
      return '待处理'
    case 'processing':
      return '处理中'
    case 'completed':
      return '已处理'
    case 'ignored':
      return '已忽略'
    default:
      return '未知'
  }
}

// 加载异常列表
const loadExceptionList = async () => {
  loading.value = true
  try {
    const params = {
      ...searchForm,
      page: pagination.page,
      size: pagination.size
    }
    const response = await qualityStore.fetchExceptionList(params)
    exceptionList.value = response.list
    pagination.total = response.total
  } catch (error) {
    ElMessage.error('加载异常列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理
const handleSearch = () => {
  pagination.page = 1
  loadExceptionList()
}

// 重置处理
const handleReset = () => {
  pagination.page = 1
  loadExceptionList()
}

// 分页处理
const handlePageChange = (page: number) => {
  pagination.page = page
  loadExceptionList()
}

const handleSizeChange = (size: number) => {
  pagination.size = size
  pagination.page = 1
  loadExceptionList()
}

// 选择处理
const handleSelectionChange = (selection: QualityException[]) => {
  selectedRows.value = selection
}

// 处理异常
const handleProcess = (row: QualityException) => {
  currentException.value = row
  processDialogVisible.value = true
}

// 查看详情
const handleViewDetail = (row: QualityException) => {
  currentException.value = row
  detailDialogVisible.value = true
}

// 处理提交
const handleProcessSubmit = async (data: any) => {
  try {
    // 调用处理API
    // await processException(data)
    ElMessage.success('处理成功')
    processDialogVisible.value = false
    loadExceptionList()
  } catch (error) {
    ElMessage.error('处理失败')
  }
}

// 批量处理
const handleBatchProcess = async () => {
  try {
    await ElMessageBox.confirm(
      `确定要批量处理选中的 ${selectedRows.value.length} 条异常记录吗？`,
      '批量处理',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )

    // 调用批量处理API
    ElMessage.success('批量处理成功')
    loadExceptionList()
  } catch (error) {
    // 用户取消
  }
}

// 导出数据
const handleExport = () => {
  ElMessage.info('导出功能开发中...')
}

// 新增异常处理
const handleCreateException = async () => {
  createExceptionDialogVisible.value = true
  await loadDeliveryRecords()
}

// 加载投递记录
const loadDeliveryRecords = async () => {
  try {
    const response = await qualityStore.fetchDeliveryRecords(deliverySearchForm)
    deliveryRecords.value = response.list
  } catch (error) {
    ElMessage.error('加载投递记录失败')
  }
}

// 处理投递记录搜索
const handleDeliverySearch = () => {
  loadDeliveryRecords()
}

// 选择投递记录
const handleDeliveryRecordSelect = (record: UserDeliveryRecord | null) => {
  selectedDeliveryRecord.value = record
  if (record) {
    createExceptionForm.deliveryRecordId = record.id
  }
}

// 提交创建异常
const handleCreateExceptionSubmit = async () => {
  if (!selectedDeliveryRecord.value) {
    ElMessage.warning('请先选择一条投递记录')
    return
  }

  if (!createExceptionForm.reason.trim()) {
    ElMessage.warning('请输入异常原因')
    return
  }

  try {
    await qualityStore.createException(createExceptionForm)
    ElMessage.success('异常创建成功')
    createExceptionDialogVisible.value = false
    resetCreateExceptionForm()
    loadExceptionList()
  } catch (error) {
    ElMessage.error('创建异常失败')
  }
}

// 扫码处理布袋编号
const handleScanBagNumber = () => {
  ElMessage.info('扫码功能开发中...')
}

// 重置创建异常表单
const resetCreateExceptionForm = () => {
  selectedDeliveryRecord.value = null
  createExceptionForm.deliveryRecordId = 0
  createExceptionForm.type = 'weight_error'
  createExceptionForm.description = ''
  createExceptionForm.adjustAmount = 0
  createExceptionForm.reason = ''
}



// 更多操作
const handleMoreAction = async (command: string, row: QualityException) => {
  switch (command) {
    case 'ignore':
      try {
        await ElMessageBox.confirm('确定要忽略这条异常记录吗？', '忽略异常', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        ElMessage.success('已忽略')
        loadExceptionList()
      } catch (error) {
        // 用户取消
      }
      break
    case 'reassign':
      ElMessage.info('重新分配功能开发中...')
      break
    case 'history':
      ElMessage.info('处理历史功能开发中...')
      break
  }
}

onMounted(() => {
  loadExceptionList()
})
</script>

<style lang="scss" scoped>
.create-exception-dialog {
  .delivery-records-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }

    .search-bar {
      display: flex;
      gap: 12px;
      margin-bottom: 12px;
    }
  }

  .exception-form-section {
    margin-bottom: 24px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }

    .amount-hint {
      margin-left: 12px;
      font-weight: bold;

      &.positive {
        color: #67C23A;
      }

      &.negative {
        color: #F56C6C;
      }
    }
  }

  .dialog-actions {
    display: flex;
    justify-content: flex-end;
    gap: 12px;
    padding-top: 20px;
    border-top: 1px solid #ebeef5;
  }
}
.action-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 16px 20px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 1px 2px rgba(0, 0, 0, 0.05);

  .action-left,
  .action-right {
    display: flex;
    gap: 12px;
  }
}

.text-secondary {
  font-size: 12px;
  color: #909399;
}

.text-ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.image-error {
  width: 40px;
  height: 40px;
  display: flex;
  align-items: center;
  justify-content: center;
  background: #f5f7fa;
  border-radius: 4px;
  color: #909399;
  font-size: 12px;
}

.image-count {
  margin-left: 4px;
  font-size: 12px;
  color: #409eff;
  font-weight: bold;
}

.exception-detail {
  .exception-images {
    margin-top: 20px;

    h4 {
      margin: 0 0 12px 0;
      color: #303133;
    }

    .images-grid {
      display: grid;
      grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
      gap: 12px;

      .exception-image {
        width: 120px;
        height: 120px;
        border-radius: 4px;
        cursor: pointer;
      }
    }
  }
}

@media (max-width: 768px) {
  .action-bar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;

    .action-left,
    .action-right {
      justify-content: center;
    }
  }
}
</style>
